<?php
declare(strict_types=1);

namespace app\controller\admin;

use app\BaseController;
use app\model\{MerchantWithdrawRecord, UserWithdrawRecord};
use app\service\{WechatService, AlipayService};
use think\facade\{Db, Log};
use think\Request;

class WithdrawController extends BaseController
{
    /**
     * 获取商家提现列表
     */
    public function merchantList(Request $request)
    {
        $where = [];
        
        // 游标ID
        $last_id = (int)$request->param('last_id', 0);
        if ($last_id > 0) {
            $where[] = ['id', '<', $last_id];
        }
        
        // 商家ID筛选
        if ($merchant_id = $request->param('merchant_id')) {
            $where[] = ['merchant_id', '=', $merchant_id];
        }
        
        // 提现状态筛选
        if ($status = $request->param('status')) {
            $where[] = ['status', '=', $status];
        }
        
        // 时间范围筛选
        if ($start_time = $request->param('start_time')) {
            $where[] = ['create_time', '>=', $start_time];
        }
        if ($end_time = $request->param('end_time')) {
            $where[] = ['create_time', '<=', $end_time];
        }
        
        // 每页条数
        $limit = (int)$request->param('limit', 15);
        
        $list = MerchantWithdrawRecord::where($where)
            ->with(['merchant'])
            ->order('id', 'desc')
            ->limit($limit + 1)
            ->select();
            
        $has_more = false;
        if (count($list) > $limit) {
            $has_more = true;
            $list = array_slice($list->toArray(), 0, $limit);
        } else {
            $list = $list->toArray();
        }
        
        // 获取下一页的游标ID
        $next_id = 0;
        if ($has_more && !empty($list)) {
            $next_id = end($list)['id'];
        }
        
        // 统计数据
        $stats = [
            'total_count' => MerchantWithdrawRecord::where($where)->count(),
            'total_amount' => MerchantWithdrawRecord::where($where)->sum('withdraw_amount'),
            'pending_count' => MerchantWithdrawRecord::where('status', 0)->count()
        ];
        
        return $this->success('获取成功', [
            'list' => $list,
            'has_more' => $has_more,
            'next_id' => $next_id,
            'stats' => $stats
        ]);
    }
    
    /**
     * 审核商家提现
     */
    public function auditMerchant(Request $request, $id)
    {
        $data = $this->validate($request->post(), [
            'status' => 'require|in:1,2',  // 1通过 2拒绝
            'remark' => 'require|max:255'
        ]);
        
        Db::startTrans();
        try {
            $withdraw = MerchantWithdrawRecord::where('status', 0)->find($id);
            if (!$withdraw) {
                throw new \Exception('提现记录不存在或已审核');
            }
            
            if ($data['status'] == 1) {
                // 通过则执行转账
                $result = $this->handleTransfer($withdraw);
                if (!$result) {
                    throw new \Exception('转账失败');
                }
            } else {
                // 拒绝则退回余额
                $withdraw->merchant->inc('balance', $withdraw->withdraw_amount)->update();
            }
            
            $withdraw->save([
                'status' => $data['status'],
                'audit_time' => date('Y-m-d H:i:s'),
                'audit_remark' => $data['remark']
            ]);
            
            Db::commit();
            return $this->success('审核成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }
    
    /**
     * 处理转账
     */
    protected function handleTransfer($withdraw)
    {
        if ($withdraw->withdraw_account_type == 'wechat') {
            $wechatService = new WechatService($withdraw->merchant_id);
            return $wechatService->transfer([
                'out_trade_no' => $withdraw->withdraw_no,
                'openid' => $withdraw->withdraw_account,
                'amount' => $withdraw->withdraw_amount * 100,
                'desc' => '商家提现'
            ]);
        } else if ($withdraw->withdraw_account_type == 'alipay') {
            $alipayService = new AlipayService($withdraw->merchant_id);
            return $alipayService->transfer([
                'out_trade_no' => $withdraw->withdraw_no,
                'account' => $withdraw->withdraw_account,
                'real_name' => $withdraw->withdraw_name,
                'amount' => $withdraw->withdraw_amount
            ]);
        }
        
        return false;
    }
    
    /**
     * 获取用户提现列表
     */
    public function userList(Request $request)
    {
        // 实现类似商家提现列表的逻辑
        // ...
    }
    
    /**
     * 审核用户提现
     */
    public function auditUser(Request $request, $id)
    {
        // 实现类似商家提现审核的逻辑
        // ...
    }
} 